/**
 * @Title: VolleyBasic.java
 * @Copyright: XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * @Description: TODO<请描述此文件是做什么的>
 * @author: MeiYi
 * @data: 2016-4-6 下午1:46:21
 * @version: V1.0
 */

package artid.com.arttogo.network;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.NetworkImageView;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import artid.com.arttogo.R;
import artid.com.arttogo.bean.AppItem;
import artid.com.arttogo.bean.PersonalCenter;

/**
 * TODO<请描述这个类是干什么的>
 *
 * @author 熊彬
 * @data: 2016-4-6 下午1:46:21
 * @version: V1.0
 */
public class VolleyBasic {

    private static VolleyBasic vb;
    private Activity activity;
    public static Dialog progressDialog;
    public static Boolean isShowDialog = true;

    private VolleyBasic() {

    }

    /**
     * 获取类实例对象
     *
     * @return MyActivityManager
     */
    public static VolleyBasic getInstance(Activity activity) {
        // if (null == vb) {
        vb = new VolleyBasic();
        // }
        vb.activity = activity;
        isShowDialog = true;
        return vb;
    }

    public static VolleyBasic getInstanceNoDialog(Activity activity) {
        isShowDialog = false;
        vb = new VolleyBasic();
        vb.activity = activity;
        return vb;
    }


    private String url;
    private Map<String, String> parameter;
    private VolleyCallback callBcak;
    private Class<? extends AppItem> cls;

    /**
     *
     */
    public void post(String url, Map<String, String> parameter,
                     Class<? extends AppItem> cls, VolleyCallback callBcak) {
        // TODO Auto-generated method stub
        this.url = url;
        this.parameter = parameter;
        this.callBcak = callBcak;
        this.cls = cls;
        System.out.print("Posturl:" + url + " ");
        printHashMap("请求参数：", parameter);
        start(Request.Method.POST);
    }

    @SuppressLint("InflateParams")
    @SuppressWarnings("deprecation")
    public void start(int Method) {
        if (isShowDialog) {
            showLoding(activity);
        }
        VolleyRequest stringRequest = new VolleyRequest(Method, url,
                new Listener<String>() {

                    @Override
                    public void onResponse(String returnString) {

                        disMissLoding();

                        VolleyData VD = new VolleyData(returnString, cls);

                        if (!TextUtils.isEmpty(VD.getJson())) {
                            System.out.println(VD.getJson());
                        }

                        if (VD.getCode() != VolleyData.Success
                                && VD.getCode() != -99) {
                            // Toast.makeText(activity, VD.getMsg(),
                            // Toast.LENGTH_LONG).show();
                            if (cls.equals(PersonalCenter.class) || url.contains("personalCenter")) {
                                return;
                            }
                            if (!TextUtils.isEmpty(VD.getMsg())) {
                                Toast.makeText(activity, VD.getMsg(),
                                        Toast.LENGTH_LONG).show();
                            }
                            // }
                            return;
                        }
                        if (VD.getCode() == -99 && !cls.equals(PersonalCenter.class)) {
                            AppUtil.Logout(activity);
                            AppUtil.LoginVer(activity);
                            return;
                        }
                        callBcak.onSuccess(VD);
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                disMissLoding();

                System.out.print("volleyError"
                        + volleyError.getMessage());
                callBcak.onError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // 在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                return parameter != null ? parameter : map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(15000, 0, 1f));
        VolleySingleton volleySingleton = new VolleySingleton(activity);

        VolleySingleton.getVolleySingleton(activity.getApplicationContext())
                .addToRequestQueue(stringRequest);
    }

    static ImageView fireImg;

    public static void showLoding(Context activity) {
        if (progressDialog == null) {
            LayoutInflater inflater = LayoutInflater.from(activity);
            View v = inflater.inflate(R.layout.loading, null);// 得到加载view
            RelativeLayout layout = (RelativeLayout) v
                    .findViewById(R.id.rel_dialog);// 加载布局
            fireImg = (ImageView) v.findViewById(R.id.iv);
            final AnimationDrawable animDrawable = (AnimationDrawable) fireImg
                    .getBackground();
            fireImg.post(new Runnable() {
                @Override
                public void run() {
                    animDrawable.start();
                }
            });
            progressDialog = new Dialog(activity, R.style.dialog);// 创建自定义样式dialog
            progressDialog.setCancelable(false);// 不可以用“返回键”取消
            progressDialog.setContentView(layout,
                    new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.FILL_PARENT,
                            LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    public static void disMissLoding() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    public static void printHashMap(String tag, Map<String, String> hashMap) {
        Set<String> keys = hashMap.keySet();
        for (String key : keys) {
            System.out.print(tag + "===" + key + "--" + hashMap.get(key));
        }
    }

    public static ImageListener getImageListener(final NetworkImageView view,
                                                 final int defaultImageResId, final int errorImageResId,
                                                 final String url) {
        return new ImageListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (errorImageResId != 0) {
                    view.setImageResource(errorImageResId);
                }
            }

            @Override
            public void onResponse(ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() != null) {
                    // 在这里可以设置，如果想得到圆角图片的画，可以对bitmap进行加工，可以给imageview加一个
                    // 额外的参数
                    String urlTag = (String) view.getTag();
                    if (urlTag != null && urlTag.trim().equals(url)) {
                        view.setImageBitmap(response.getBitmap());
                    }
                } else if (defaultImageResId != 0) {
                    view.setImageResource(defaultImageResId);
                }
            }
        };
    }

    public static ImageListener getImageListener(final ImageView view,
                                                 final int defaultImageResId, final int errorImageResId,
                                                 final String url) {
        return new ImageListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (errorImageResId != 0) {
                    view.setImageResource(errorImageResId);
                }
            }

            @Override
            public void onResponse(ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() != null) {
                    // 在这里可以设置，如果想得到圆角图片的画，可以对bitmap进行加工，可以给imageview加一个
                    // 额外的参数
                    String urlTag = (String) view.getTag();
                    if (urlTag != null && urlTag.trim().equals(url)) {
                        view.setImageBitmap(response.getBitmap());
                    }
                } else if (defaultImageResId != 0) {
                    view.setImageResource(defaultImageResId);
                }
            }
        };
    }
}
